﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using System.Windows.Forms;
using log4net;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using static CloudApiServer.Controllers.DemoController;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 电子凭证接口返回控制器.
    /// </summary>
    [RoutePrefix("localcfc/api")]
    public class FsiEccCodeController : ApiController
    {
        /// <summary>
        /// 未被定义的接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// hsecfc/localQrCodeQuery
        [Route("hsecfc/localQrCodeQuery")]
        [HttpPost]
        public async Task<IHttpActionResult> localQrCodeQuery(HttpRequestMessage request)
        {
            string orgid="";
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestEccCodeHeader<DataEcCodeRequest>>(request.Content.ReadAsStringAsync().Result);
                    orgid = fsiRequest.orgId;
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dt = new DataTable();
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_PsnInfo where certno=@certno";
                        cmd.Parameters.AddWithValue("@certno", FsiDatainfo.Ecccodecardno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count == 1)
                            {
                                var FsiHeader = new FsiEcCodeHeader<DataFsiEccCode>
                                {
                                    code = 0,
                                    message = "成功",
                                    orgId = orgid,
                                    data = new DataFsiEccCode
                                    {
                                        chnlId = PublicMethod.GenerateRandomString(32),
                                        ecIndexNo = PublicMethod.GenerateRandomString(32),
                                        ecQrCode = PublicMethod.GenerateRandomString(28),
                                        ecToken = PublicMethod.GenerateRandomString(38),
                                        idNo = FsiDatainfo.Ecccodecardno,
                                        idType = "01",
                                        insuOrg = "",
                                        userName = dt.Rows[0]["psn_name"].ToString(),
                                    }
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception($"查询人员信息表失败！根据传入的人员证件号码【{FsiDatainfo.Ecccodecardno}】查询到的人员信息总数为：{dt.Rows.Count}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiEcCodeHeader<DataFsiEccCode>
                    {
                        code = -1,
                        message = $"[{Errnum}]调用电子凭证自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                        orgId = orgid

                    };
                    LogHelper.Error( $"[{Errnum}]调用电子凭证自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }



        }

    }
}
